package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.dto.DishFlavorDto;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.itheima.vo.DishVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @Author HeiMa-sw
 * @Description 菜品操作控制层//TODO 17210
 * @Date 9:34 2022/6/8
 **/
@RestController
@EnableCaching
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;

    @GetMapping("/page")
    public R<DishVo> dishPage(Integer page, Integer pageSize, String name) {
        DishVo pageInfo = dishService.getPage(page, pageSize, name);
        return R.success(pageInfo);
    }

    @GetMapping("/list")
    public R<List<Dish>> dishList(String categoryId, String name) {
        List<Dish> dishList = dishService.getList(categoryId, name);
        return R.success(dishList);
    }

    @GetMapping("/{id}")
    public R<DishFlavorDto> dishId(@PathVariable String id) {
        Dish dish = dishService.getById(id);
        List<DishFlavor> dishFlavors = dishFlavorService.getByDishId(id);
        DishFlavorDto dishFlavorDto = new DishFlavorDto();
        BeanUtils.copyProperties(dish, dishFlavorDto);
        dishFlavorDto.setFlavors(dishFlavors);
        return R.success(dishFlavorDto);
    }

    @PostMapping
    @CacheEvict(value = "dish" ,allEntries = true)
    public R<DishFlavorDto> saveDish(@RequestBody DishFlavorDto dishFlavorDto) {
        try {
            dishService.saveOne(dishFlavorDto);
            return R.success(dishFlavorDto);
        } catch (Exception e) {
            return R.error(e.getMessage());
        }
    }

    @PutMapping
    @CacheEvict(value = "dish" ,allEntries = true)
    public R<String> modifyDish(@RequestBody DishFlavorDto dishFlavorDto) {
        dishService.modifyOne(dishFlavorDto);
        return R.success("更新成功");
    }

    @DeleteMapping
    @CacheEvict(value = "dish" ,allEntries = true)
    public R<String> removeDish(String[] ids) {
        dishService.batchRemove(ids);
        dishFlavorService.batchRemove(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> modifyStatus(@PathVariable Integer status, @RequestParam("ids") String[] ids) {
        dishService.modifyStatus(status, ids);
        return R.success("操作成功");
    }
}
